<template>
  <div class="all-wrap">
    <div class="all-title">用户管理</div>
    <div class="top-controllers" style="margin-bottom: 4px;">
      <el-input v-model="searchValue" clearable class="w-50 m-2" placeholder="请输入用户名" />
      <el-button type="primary" @click="searchClick">搜索</el-button>
      <el-button type="primary" @click="addUser">新增</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="username" label="Username" />
      <el-table-column prop="address" label="Address" />
      <el-table-column prop="email" label="Email" />
      <el-table-column prop="phone" label="Phone" />
      <el-table-column label="Roles">
        <template #default="scope">
          <el-tag v-for="(item, index) in scope.row.roles" :key="index">{{ item.roleName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Controllers" width="280">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editData(scope.row)">修改</el-button>
          <el-button type="primary" size="small" @click="editRole(scope.row)">编辑角色</el-button>
          <el-popconfirm width="220" confirm-button-text="OK" cancel-button-text="No, Thanks" :icon="InfoFilled"
            icon-color="#626AEF" title="Are you sure to delete this?" @confirm="confirmEvent(scope.row)">
            <template #reference>
              <el-button>Delete</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-pagination v-model:current-page="currentPage" :page-size="10" layout="total, prev, pager, next" :total="parseInt(dataTotal+'')"
      @current-change="handleCurrentChange" />
    <el-dialog v-model="dialogFormVisible" :title="dialogState">
      <el-form :model="form" ref="ruleFormRef" label-width="100" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-show="dialogState == '新增用户'">
          <el-input v-model="form.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-show="dialogState == '新增用户'">
          <el-input type="password" v-model="form.confirmPassword" autocomplete="off" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" type="number" min="0" autocomplete="off" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogRole" title="修改角色">
      <el-select v-model="roles" multiple placeholder="Select" style="width: 100%">
        <el-option v-for="item in rolesOptions" :key="item.id" :label="item.roleName" :value="item.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEditRole(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submitEditRole(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onBeforeMount, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { getUserList, addUserFn, EditUserFn, DeleteUserFn,EditUserRole } from '../apis/user'
import {getRoleList} from '../apis/role'
import md5 from 'js-md5'
interface option {
  id:number
  roleName:string
}
interface Role {}
let searchValue = ref("")
let tableData = ref([])
let currentPage = ref(1)
let dataTotal = ref(0)
let editDataId = ref(0)
let rolesOptions=ref<option[]>([])
let dialogFormVisible = ref(false)
let dialogState = ref("新增用户")
let dialogRole=ref(false)
let editUserId=ref('')
let roles=ref([])
const ruleFormRef = ref<FormInstance>()
const confirmPassword2=(rule,value,callback)=>{
  if(value==form.password){
    callback()
  }else{
    callback(new Error("请输入正确密码"))
  }
}
let form = reactive({
  username: '',
  age: 0,
  email: '',
  phone: '',
  address: '',
  password:'',
  confirmPassword:''
})
let rules = reactive({
  username: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Length should be 2 to 50', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 50, message: 'Length should be 6 to 50', trigger: 'blur' },
  ],
  confirmPassword:[
    { required: true, message: '请再次输入密码', trigger: 'input' },
    { validator: confirmPassword2},
  ],
  age: [
    {
      required: false,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  email: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  phone: [
    {
      required: false,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ],
  address: [
    {
      required: false,
      message: 'Please select Activity zone',
      trigger: 'change',
    },
  ]
})
const handleCurrentChange = () => {
  getData()
}
onMounted(async() => {
  getData()
  let res=await getRoleList({"pageSize":999})
  if(res.status==200){
    rolesOptions.value=res.data.data
  }
})
const getData = async () => {
  let params = {
    "username": searchValue.value,
    "page": currentPage.value,
  }
  let res = await getUserList(params)
  if (res.status == 200) {
    tableData.value = res.data.data
    dataTotal.value = res.data.total - 0
  }
}
const searchClick = () => {
  currentPage.value = 1
  getData()
}
const addUser = () => {
  dialogState.value = "新增用户"
  dialogFormVisible.value = true
}
const clearForm = (form) => {
  let empty = {}
  for (let i in form) {
    empty[i] = ''
  }
  Object.assign(form, empty)
}
const cancel = (formEl) => {
  if (!formEl) return
  clearForm(form)
  dialogFormVisible.value = false
}
const cancelEditRole = (formEl) =>{
  roles.value=[]
  dialogRole.value = false
}
const submitEditRole = async(ruleFormRef) =>{
  let params={
    id:editUserId.value,
    roleIds:roles.value.join(",")
  }
  let res=await EditUserRole(params)
  if (res.status==200){
    ElMessage({
      message: '修改用户角色成功',
      type: 'success',
    })
    getData()
    dialogRole.value = false
    roles.value=[]
  }
}
const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialogState.value == "新增用户") {
        let res = await addUserFn(form)
        if (res.status == 200) {
          ElMessage({
            message: '新增用户成功',
            type: 'success',
          })
          getData()
        }
      } else {
        let res = await EditUserFn({ id: editDataId.value, ...form })
        if (res.status == 200) {
          ElMessage({
            message: '修改用户成功',
            type: 'success',
          })
          getData()
        } else {
          ElMessage({
            message: '修改用户失败',
            type: 'error',
          })
        }
      }
      clearForm(form)
      dialogFormVisible.value = false
    } else {
      console.log('error submit!', fields)
      ElMessage({
        message: '数据不正确',
        type: 'error',
      })
    }
  })
}
const editData = (row) => {
  dialogState.value = "修改用户"
  editDataId.value = row.id
  dialogFormVisible.value = true
  form = reactive({
    ...row,
    confirmPassword:row.password
  })
}
const editRole=(row)=>{
  dialogRole.value=true
  editUserId.value=row.id
  roles.value=row.roles.map(e=>e.id)
}
const confirmEvent = async (row) => {
  let res = await DeleteUserFn({ id: row.id })
  if (res.status == 200) {
    ElMessage({
      message: '删除用户成功',
      type: 'success',
    })
    getData()
  } else {
    ElMessage({
      message: '删除用户失败',
      type: 'error',
    })
  }
  getData()
}
</script>
<style lang="less" scoped>
.top-controllers {
  width: 100%;
  height: 30px;

  .w-50 {
    width: 200px;
    margin-right: 20px;
  }
}
</style>